import {SubPhaseName, TableSubPhaseBase, timeLeft} from "./base";
import {autoSerialize} from "../../serializeDecorator";
import NormalTable from "../normalTable";

export class DelayPhase extends TableSubPhaseBase {
  timer: NodeJS.Timer

  @autoSerialize
  delayStartAt: number = 0

  @autoSerialize
  delayInMs: number = 0


  constructor(readonly table: NormalTable, delayInMs: number) {
    super(table)
    this.delayInMs = delayInMs
  }

  name(): SubPhaseName {
    return 'DelayPhase';
  }

  resume({delayStartAt}) {
    this.delayStartAt = delayStartAt
    if (delayStartAt > 0) {

      this.timer = setTimeout(() => {
        this.leaveDelayPhase()
      }, timeLeft(delayStartAt, this.delayInMs))
    } else {
      this.onEntry()
    }
  }

  private leaveDelayPhase() {
    this.table.nextPhase()
  }

  onEntry() {
    this.delayStartAt = Date.now()
    this.timer = setTimeout(() => {
      this.leaveDelayPhase()
    }, this.delayInMs)
  }

  onLeave() {
    clearTimeout(this.timer)
  }
}
